﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Models;
using BLL.TWTZ;
using System.Data;
using System.Web;
using System.IO;
using BLL.Base;
using BLL;
using BLL.Report;

namespace YQFK.Controllers
{
    public class TwtzController : ApiController
    {
        private TwtzBLL twtzbll = new TwtzBLL();
        private readonly FileBLL _fileBll = new FileBLL();
        // GET: api/Twtz
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/Twtz/5
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/Twtz
        public void Post([FromBody]string value)
        {
        }

        // PUT: api/Twtz/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE: api/Twtz/5
        public void Delete(int id)
        {
        }


        /// <summary>
        /// 获取测温列表
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        //[Route("api/Twtz/GetList")]
        [HttpPost]
        public object GetList(JObject jitem)
        {
            try
            {
                string jsonString = JsonConvert.SerializeObject(jitem);
                var jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonString);
                int pageSize = Convert.ToInt32(jsonParams.pageSize); 
                int pageIndex = Convert.ToInt32(jsonParams.pageIndex);
                string unitid = jsonParams.unitid;
                string persontype = jsonParams.persontype; //人员类型  劳务人员  管理人员
                string personname = jsonParams.personname;//人员姓名
                string beginTime = jsonParams.beginTime;//开始时间
                string endTime = jsonParams.endTime;//结束时间
                string fieldNames = "a.twtzid,a.Operatetime,b.Temperature,b.TemperaturePersonName,b.TemperaturePersonId,b.UnitName,c.age,c.Gender";
                string pkId = "b.id";
                string tableName = "twtz a left join TemperaturePerson b on cast(a.twtzid as nvarchar(64)) = b.TwtzId left join employee c on b.TemperaturePersonId=c.EmployeeId";
                string strWhere = string.Format(" a.unitId='{0}' and c.EmployeeType='{1}'", unitid, persontype);
                if (!string.IsNullOrEmpty(personname))
                {
                    strWhere += string.Format(" and b.TemperaturePersonname like '%{0}%'", personname);
                }
                if (!string.IsNullOrEmpty(beginTime) && !string.IsNullOrEmpty(endTime))
                {
                    strWhere += " and a.Operatetime  between  '" + beginTime + "' and  '" + endTime + "'";
                }
                if (!string.IsNullOrEmpty(beginTime) && string.IsNullOrEmpty(endTime))
                {
                    strWhere += " and  DATEDIFF(DD,a.Operatetime,'" + beginTime + "')=0";
                }
                string sidx = "a.Operatetime";
                string sort = "desc";
                int total = 0;
                int records = 0;
                DataTable dt = new DataTable();
                dt = twtzbll.GetPageList(pageSize, pageIndex, tableName, fieldNames, pkId, strWhere, sort, sidx, out total, out records);
                dt.Columns.Add("imgurl");
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string imgUrl = "";
                    AttachmentModel am = new LoginUserBll().GetAttachmentById(dt.Rows[i]["TemperaturePersonId"].ToString());
                    if (am != null && am.AttachmentId.ToString() != "00000000-0000-0000-0000-000000000000")
                    {
                        imgUrl = Url.Link("DefaultApi", new { id = am.AttachmentId, controller = "Attachment", action = "Get" });
                    }
                    dt.Rows[i]["imgurl"] = imgUrl;
                }

                return new { code = 0, count = records, info = "获取数据成功", data = dt };
            }
            catch (Exception ex)
            {
                return new { code = -1, count = 0, info = "获取数据失败" };
            }
        }

        /// <summary>
        /// 保存体温台账(新增、修改)
        /// </summary>
        /// <returns></returns>
        //[Route("api/Twtz/SaveTwtz")]
        [HttpPost]
        public object SaveTwtz()
        {
            try
            {
                var res = System.Web.HttpContext.Current.Request["json"];
                
                dynamic dy = JsonConvert.DeserializeObject<ExpandoObject>(res);

                TwtzModel entity = new TwtzModel();
                entity = JsonConvert.DeserializeObject<TwtzModel>(JsonConvert.SerializeObject(dy.data));
                entity.TwtzId = string.IsNullOrEmpty(entity.TwtzId) ? Guid.NewGuid().ToString() : entity.TwtzId;
                entity.TotalPerson = entity.TemperaturePerson.Count;
                int AbnormalPerson = 0;
                foreach (var item in entity.TemperaturePerson)
                {
                    if ((double)item.Temperature > 37.2)
                    {
                        AbnormalPerson += 1;
                    }
                }
                entity.AbnormalPerson = AbnormalPerson;
                entity.NormalPerson = entity.TotalPerson - entity.AbnormalPerson;
                //计算上报人数、疑似人数
                int fillInNum = new ReportOnEpidemicSituationBLL().GetFillInNum(entity.OperateTime,entity);
                int suspectedNum = new ReportOnEpidemicSituationBLL().GetSuspectedNum(entity.OperateTime, entity);
                ReportOnEpidemicSituationModel thm = new ReportOnEpidemicSituationModel();
                thm.DepartId = entity.UnitId;
                thm.DepartName = entity.UnitName;
                thm.userName = entity.RecordPersonName;
                thm.userId = entity.RecordPersonId;
                thm.FillInDate = entity.OperateTime;
                thm.FillInNum = fillInNum;
                thm.AddSuspectedNum = suspectedNum;
                if (new ReportOnEpidemicSituationBLL().InsertReport(thm) == false)
                {
                    throw new Exception("体温上报汇总出错");
                }
                twtzbll.SaveTwtz(entity);
                HttpFileCollection files = HttpContext.Current.Request.Files;
                if (files != null && files.Count > 0)
                {
                    List<FileModel> insertList = new List<FileModel>();
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFile file = files[i];
                        var filename = file.FileName;
                        var fileExtend = filename.Substring(filename.LastIndexOf(".")).ToLower();


                        var serverPath = $"~/AppFile/Twtz/{DateTime.Now.ToString("yyyy-MM-dd")}/";
                        var savePath = HttpContext.Current.Server.MapPath(serverPath);
                        if (!Directory.Exists(savePath))
                        {
                            Directory.CreateDirectory(savePath);
                        }
                        string realName = Guid.NewGuid() + fileExtend;
                        file.SaveAs(savePath + realName);
                        FileModel insertModel = new FileModel()
                        {
                            Id = Guid.NewGuid(),
                            CreateTime = DateTime.Now,
                            FileName = realName,
                            FileType = fileExtend,
                            RealName = filename,
                            RecId = entity.TwtzId,
                            FilePath = serverPath + realName
                        };
                        insertList.Add(insertModel);
                    }

                    _fileBll.SaveFile(insertList);
                }

                return new { code = 0, count = 0, info = "保存成功" };
            }
            catch (Exception ex)
            {
                return new { code = -1, count = 0, info = "保存失败" };
            }
            
        }

        /// <summary>
        /// 获取体温台账对象
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        //[Route("api/Twtz/GetTwtzEntity")]
        [HttpPost]
        public object GetTwtzEntity(JObject jitem)
        {
            try
            {
                string jsonString = JsonConvert.SerializeObject(jitem);
                var jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonString);
                string id = jsonParams.id;
                TwtzModel entity = twtzbll.GetEntity(id);
                entity.TemperaturePerson = twtzbll.GetTemperaturePersonList(id);
                List<Guid> recid = new List<Guid>();
                System.Guid guid = new Guid(id);
                recid.Add(guid);
                //获取附件信息
                List<FileModel> files = _fileBll.GetFile(recid).ToList();
                files.ForEach(file => {
                    file.FilePath = Url.Content(file.FilePath);
                });
                entity.files = files;
                return new { code = 0, count = 0, info = "获取成功", data = entity };
            }
            catch (Exception ex)
            {
                return new { code = -1, count = 0, info = "获取失败" };
            }

        }

        /// <summary>
        /// 获取首页测温统计
        /// </summary>
        /// <param name="jitem"></param>
        /// <returns></returns>
        //[Route("api/Twtz/GetDecktopTW")]
        [HttpPost]
        public object GetDecktopTW(JObject jitem)
        {
            try
            {
                string jsonString = JsonConvert.SerializeObject(jitem);
                var jsonParams = JsonConvert.DeserializeObject<dynamic>(jsonString);
                string unitid = jsonParams.unitid;
                int lwcw = twtzbll.GetTemperaturePersonList(unitid, "劳务人员");
                int glcw = twtzbll.GetTemperaturePersonList(unitid, "管理人员");
                int[] yc = new TemperatureHighBll().GetTotalCountByDepartId(unitid);
                var data = new
                {
                    glcw = glcw, //管理人员测温统计
                    lwcw = lwcw, //劳务人员测温统计
                    cwzj = glcw + lwcw, //测温总计
                    glquarantine = yc[0],//今日管理人员隔离人数
                    lwquarantine = yc[1],//今日劳务人员隔离人数
                    glquarantineAdd = yc[0]-yc[2],//管理人员隔离人数较昨日新增
                    lwquarantineAdd = yc[1]-yc[3],//劳务人员较昨日新增
                    quarantineCount = yc[0] + yc[1],//今日隔离总数
                    quarantineCountAdd = yc[0] + yc[1]-yc[2]-yc[3],//今日隔离总数较昨日新增
                    glyc=yc[4],//今日管理异常人数
                    lwyc=yc[5],//今日劳务异常人数
                    glycAdd=yc[4]-yc[6],//较昨日管理异常新增人数
                    lwycAdd=yc[5]-yc[7],//较昨日劳务异常新增人数
                    glycCount=yc[4]+yc[5],//异常人数总数
                    glycCountAdd=yc[4]+yc[5]-yc[6]-yc[7]//较昨日新增的异常总数
                };
                return new { code = 0, count = 0, info = "获取成功", data = data };
            }
            catch (Exception ex)
            {
                return new { code = -1, count = 0, info = "获取失败" };
            }
        }

        /// <summary>
        /// 删除体温台账
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public object RemoveTwtz([FromBody]JObject json)
        {
            try
            {
                string res = json.Value<string>("json");

                dynamic dy = JsonConvert.DeserializeObject<ExpandoObject>(res);

                twtzbll.RemoveTwtz(dy.data.id);
                return new { code = 0, count = 0, info = "删除成功" };
            }
            catch (Exception)
            {

                throw;
            }

        }


        

        /// <summary>
        /// 获取当前节点下的子集合
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public object GetListByUnitId([FromBody]JObject json)
        {
            try
            {
                string res = json.Value<string>("json");

                dynamic dy = JsonConvert.DeserializeObject<ExpandoObject>(res);
                List<TwtzModel> entity = twtzbll.GetListByUnitId(dy.data.id);

                return new { code = 0, count = 0, info = "删除成功", data = entity };
            }
            catch (Exception)
            {

                throw;
            }

        }

        ///// <summary>
        ///// 获取所有体温台账信息
        ///// </summary>
        ///// <param name="json"></param>
        ///// <returns></returns>
        //public object GetList([FromBody]JObject json)
        //{
        //    try
        //    {
        //        string res = json.Value<string>("json");

        //        List<TwtzModel> entity = twtzbll.GetList();

        //        return new { code = 0, count = 0, info = "删除成功", data = entity };
        //    }
        //    catch (Exception)
        //    {

        //        throw;
        //    }

        //}

        ///// <summary>
        ///// 上传附件
        ///// </summary>
        ///// <param name="files"></param>
        //public void UploadFile(HttpFileCollection files)
        //{
        //    string uploadPath = HttpContext.Current.Server.MapPath("~/File/");
        //    for (int i = 0; i < files.AllKeys.Length; i++)
        //    {
        //        string fileExtension = Path.GetExtension(files[i].FileName);// 文件扩展名
        //        string fileName = Guid.NewGuid().ToString() + fileExtension;// 名称
        //        string filePath = uploadPath + files[i].FileName;// 上传路径

        //        //如果目录不存在则现要创建
        //        if (!File.Exists(uploadPath))
        //        {
        //            Directory.CreateDirectory(uploadPath);
        //        }
        //        files[i].SaveAs(filePath);
        //    }
        //}
    }
}
